import {
  Component,
  computed,
  effect,
  Injector,
  OnInit,
  signal,
} from '@angular/core';

@Component({
  standalone: true,
  selector: 'app-sn-tab',
  template: `@for (tab of tables(); track tab.name) {
    <button
      class="mr-4 pb-2 text-gray-600"
      [class]="{
        'tab-selected': tab.selected,
        'hover-with-theme': !tab.selected
      }"
      (click)="handleClick($event)"
    >
      {{ tab.name }}
    </button>
    } `,
  styleUrl: `./sn-tab.component.css`,
})
export class SnTabComponent /** implements OnInit */ {
  tables = signal([
    { name: '推荐', selected: true, index: 0 },
    { name: '最新', selected: false, index: 1 },
    { name: '热门', selected: false, index: 2 },
    { name: '精华', selected: false, index: 3 },
    { name: '关注', selected: false, index: 4 },
    { name: '订阅', selected: false, index: 5 },
  ]);
  oldSelected = computed(() =>
    this.tables().findIndex((tab) => tab.selected === true)
  );

  constructor(private injector: Injector) {
    // effect(() => {
    //   console.log('tables',this.tables())
    // })
    effect(() => {
      console.log('tables', this.oldSelected());
    });
  }
  handleClick(e: Event) {
    const target = (e.target as HTMLButtonElement).textContent!.trim();
    // 太脏检测了
    this.tables.update((value) =>
      // 这里没有使用 定向更新，因为太麻烦，且没有防御性
      value.map((tab) => ({
        ...tab,
        selected: tab.name === target,
      }))
    );
  }
}
